package com.liujit.pay.wx.api;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liujit.pay.common.domain.result.PayResult;
import com.liujit.pay.common.enums.RequestMethod;
import com.liujit.pay.wx.domain.result.RefundsResult;
import com.liujit.pay.wx.enums.PayApi;
import com.liujit.pay.wx.enums.ReturnCode;
import com.liujit.pay.wx.kit.HttpKit;
import com.liujit.pay.wx.kit.RefundsKit;
import com.liujit.pay.wx.kit.WxPayKit;
import com.liujit.pay.wx.properties.PayProperties;

/**
 * @description: 微信查询退款相关接口
 * @author: liujun
 * @create: 2021-02-22 11:21
 */
public class WxQueryRefundsApi {

    /**
     * 查询单笔退款
     *
     * @param outRefundNo 商户退款单号
     * @return
     */
    public static PayResult queryRefunds(String outRefundNo) {
        // 配置参数
        PayProperties payProperties = PayProperties.getInstance();
        // 请求地址
        String payApi = String.format(PayApi.REFUNDS_QUERY.getApi(), outRefundNo);
        // 发送请求
        String resp = queryRefunds(payApi, payProperties.getMchId(), payProperties.getKeyPath(), payProperties.getSerialNo());
        JSONObject respJson = JSONUtil.parseObj(resp);
        ReturnCode returnCode = ReturnCode.getReturnCode(respJson.getStr("code"));
        if (returnCode != null) {
            return new PayResult(returnCode.getCode(), returnCode.getMessage());
        }
        RefundsResult result = RefundsKit.getResult(respJson);
        return new PayResult(result);
    }

    /**
     * 统一下单
     *
     * @param payApi   请求地址
     * @param mchId
     * @param keyPath
     * @param serialNo
     * @return
     */
    private static String queryRefunds(String payApi, String mchId, String keyPath, String serialNo) {
        // 获取请求签名
        String authorization = WxPayKit.buildAuthorization(RequestMethod.GET, payApi, mchId, serialNo, keyPath);
        // 发送请求
        return HttpKit.get(WxPayKit.getReqUrl(payApi), authorization, serialNo);
    }
}
